onload page settings

revision:


Content

lifecycle of page onload events HTML tags DOMContentLoad window.onload window.onunload


lifecycle of page

top

The lifecycle of an HTML page has three important events:

DOMContentLoaded: the browser fully loaded HTML, and the DOM tree is built, but external resources like pictures <img> and stylesheets may not yet have loaded.

load: not only HTML is loaded, but also all the external resources: images, styles etc.

beforeunload/unload: the user is leaving the page.

Each event may be useful:

DOMContentLoaded event: DOM is ready, so the handler can lookup DOM nodes, initialize the interface.

load event: external resources are loaded, so styles are applied, image sizes are known etc.

beforeunload event: the user is leaving: we can check if the user saved the changes and ask them whether they really want to leave.

unload: the user almost left.

JavaScript examples

            <div>
                <p id="load1"></p>
                <p id="load2"></p>
            </div>
            <script>
                addEventListener('DOMContentLoaded', (event) => {
                    console.log('The DOM is fully loaded.');
                    document.getElementById("load1").innerHTML= "The DOM is fully loaded."
                });
                addEventListener('load', (event) => {
                    console.log('The page is fully loaded.');
                    document.getElementById("load2").innerHTML= "The DOM is fully loaded."
                });
                addEventListener('beforeunload', (event) => {
                    // show the confirmation dialog
                    event.preventDefault();
                    // Google Chrome requires returnValue to be set.
                    event.returnValue = '';
                });
                addEventListener('unload', (event) => {
                    // send analytic data
                });
            </script>
        

onload events

top

The onload event occurs when an object has been loaded. "onload" is most often used within the <body> element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.).

The "onload" event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

examples

code:
                    <div>
                        <p id="onload1"></p>
                    </div>
                    <script>
                        function function1(){
                            document.getElementById("onload1").innerHTML = "page is loaded";
                        }
                        function1();
                    </script>
                

assign an "onload" event to an iframe element.

code:
                    <div>
                        <p>assign an "onload" event to an iframe element.</p>
                        <iframe onload="function2()" src="demo_1.html" ></iframe>
                        <p id="onload2"></p>
                    </div>
                    <script>
                        function function2() {
                            document.getElementById("onload2").innerHTML = "iframe is loaded.";
                        }
                    </script>
                

assign an "onload" event to an iframe element.

code:
                <div>
                    <p>assign an "onload" event to an iframe element.</p>
                    <iframe id="iframe1" src="demo_1.html"></iframe>
                    <p id="onload3"></p>
                </div>
                <script>
                    document.getElementById("iframe1").onload = function() {function3()};
                    function function3() {
                        document.getElementById("onload3").innerHTML = "iframe is loaded.";
                    }
                </script>
            

use the addEventListener() method to attach a "load" event to an iframe element.

code:
                <div>
                    <p>use the addEventListener() method to attach a "load" event to an iframe element.</p>
                    <iframe id="iframe2" src="demo_1.html"></iframe>
                    <p id="onload4"></p>
                </div>
                <script>
                    document.getElementById("iframe2").addEventListener("load", function4);
                    function function4() {
                        document.getElementById("onload4").innerHTML = "iframe is loaded.";
                    }
                </script>
            

It's a good practice to use the addEventListener() method to assign the onload event handler whenever possible.


HTML tags

top

Supported HTML tags include: <body>, <frame>, <iframe>, <img>, <input type="image">, <link>, <script>, <style>

using onload on an <img> element.

code:
                <div>
                    <p>using onload on an <img> element. </p>
                    <img src="../images/1.jpg" onload="loadImage()" width="200" height="132">
                    <p id="onload5"></p>
                </div>
                <script>
                    function loadImage(){
                        document.getElementById("onload5").innerHTML = 'image loaded.'
                    }
                </script>
            

assign an "onload event handler" before setting the "src" property

code:
                <div>
                    <p>assign an "onload event handler" before setting the "src" property</p>
                    <p id="onload6"></p>
                    <div id="pic"></div>
                </div>
                <script>
                    window.addEventListener('load', () => {
                        let picture = document.createElement('img');
                        // assign and onload event handler
                        picture.addEventListener('load', (event) => {
                            document.getElementById("onload6").innerHTML = 'The picture has been loaded';
                        });
                        // add picture to the document
                        document.getElementById("pic").appendChild(picture);
                        picture.src = '../images/1.jpg';
                        picture.width = 400;
                        picture.height = 200;
                    });
                </script>
            

DOMContentLoaded

top

The "DOMContentLoaded event" happens on the document object and addEventListener must be used to catch it

JavaScript example

        document.addEventListener("DOMContentLoaded", ready);
        // not "document.onDOMContentLoaded = ..."
        <script>
            function ready() {
              alert('DOM is ready');
          
              // image is not yet loaded (unless it was cached), so the size is 0x0
              alert(`Image size: ${img.offsetWidth}x${img.offsetHeight}`);
            }
            document.addEventListener("DOMContentLoaded", ready);
        </script>
    

When the browser processes an HTML-document and comes across a <script> tag, it needs to execute before continuing building the DOM. That's a precaution, as scripts may want to modify DOM, and even "document.write" into it, so "DOMContentLoaded" has to wait and definitely happens after such scripts.

There are two exceptions from this rule:

Scripts with the "async" attributeter don't block DOMContentLoaded.
Scripts that are generated dynamically with "document.createElement('script')" and then added to the webpage also don't block this event.

External style sheets don't affect DOM, so "DOMContentLoaded" does not wait for them. But there's a pitfall. If we have a script after the style, then that script must wait until the stylesheet loads. The reason for this is that the script may want to get coordinates and other style-dependent properties of elements. Naturally, it has to wait for styles to load.


window.onload

top

The "load event" on the window object triggers when the whole page is loaded including styles, images and other resources. This event is available via the "onload property".

JavaScript example

        <script>
            window.onload = function() { // can also use window.addEventListener('load', (event) => {
                alert('Page loaded');
            
                // image is loaded at this time
                alert(`Image size: ${img.offsetWidth}x${img.offsetHeight}`);
            };
            window.onload = (event) => {
                console.log("page is fully loaded");
            };
        </script>
    

examples

How to run a function when the page is loaded in javascript?

The script has been executed. Check the console for the output.

code:
                <div>
                    <h4>How to run a function when the page is loaded in javascript? </h4>
                    <p>The script has been executed. Check the console for the output. </p>
                    <p id="onload7"></p>
                <script>
                      window.onload = function exampleFunction() { 
                        console.log('The Script will load now.'); 
                        document.getElementById("onload7").innerHTML = "The script will load now";
                    } 
                </script>
            
code:
                <div class="grid_A">
                    <div id="onload11"></div>
                    <div id="onload12"></div>
                </div>
                <style>
                    #onload11, #onload12{width: 12vw; height: 12vw; border: 0.3vw solid blue;}
                </style>
                <script>
                    document.getElementById('onload11').style.backgroundColor= "green";
                    window.onload = function(){
                        document.getElementById("onload12").style.backgroundColor = "green";
                    }
                </script>
            

window.onunload

top

When a visitor leaves the page, the "unload event" triggers on window. We can do something there that doesn't involve a delay, like closing related popup windows. The notable exception is sending analytics.


iframe onload

Example 1



code:
                <div>
                    <iframe src="demo_0.html" id='onload13' frameborder="0"></iframe><br><br>
                    <p id="first"></p>
                </div>
                <style>
                    .red-txt{color: red;}
                </style>
                <script>
                    const iframe_A = document.querySelector("#onload13");
                    iframe_A.addEventListener('load', function(){
                        iframe_A.contentDocument.body.innerHTML = "Hello"
                        iframe_A.contentDocument.body.setAttribute("style", "color: red; font-size:25px");
                    });
                    iframe_A.width = 1200;
                    iframe_A.onload = function(){
                        document.getElementById("first").innerHTML = "frame loaded";
                    }
                </script>
            

Example 2

p.s. demo_0 is used as iframe content and can be replaced by demo_2.



Click the button to change the value of the src attribute in the iframe.

code:
                <div>
                    <iframe src="demo_0.html" id='onload14' frameborder="0" width="1200px" height="150px"></iframe><br><br>
                     <p>Click the button to change the value of the src attribute in the iframe.</p>
                     <button onclick="iframeFunction()">try it</button>
                 </div>
                 <script>
                    function iframeFunction(){
                       document.getElementById("onload14").src = "demo_2.html";  
                    }
                 </script>
            

Example 3

p.s. demo_1 is used as iframe content.



Click the buttons to get the text in the appropriate language.

code:
                <div>
                    <iframe src="demo_1.html" id='onload15' frameborder="0" width="1200px" height="250px"></iframe><br><br>
                    <p>Click the buttons to get the text in the appropriate language.</p>
                    <button onclick="iframeDutch()">Dutch</button>
                    <button onclick="iframeEnglish()">English</button>
                    <button onclick="iframeChinese()">Chinese</button>
                </div>
                <script>
                    function iframeDutch(){
                        document.getElementById("onload15").contentDocument.getElementById("ned").style.display = "flex";  
                    }
                    function iframeEnglish(){
                        document.getElementById("onload15").contentDocument.getElementById("eng").style.display = "flex";  
                    }
                    function iframeChinese(){
                        document.getElementById("onload15").contentDocument.getElementById("chn").style.display = "flex";  
                    }
                </script>
            

Example 4

p.s. demo_3 is used as iframe content.



Click the buttons to get the text in the appropriate language.

code:
                <div>
                    <iframe src="demo_3.html" id='onload16' frameborder="0" width="1200px" height="250px"></iframe><br><br>
                    <p>Click the buttons to get the text in the appropriate language.</p>
                    <button onclick="iframeDutch1()">Dutch</button>
                    <button onclick="iframeEnglish1()">English</button>
                    <button onclick="iframeChinese1()">Chinese</button>
        
                </div>
                <script>
                    function iframeDutch1(){
                        var x, y, z, i;
                        var x = document.getElementById("onload16").contentWindow.document.querySelectorAll(".nederlands")
                        for (i = 0; i < x.length; i++) {
                            x[i].style.display = "flex";
                            x[i].style.color = "red";
                            x[i].style.fontSize = "20px";
                        } 
                        var y = document.getElementById("onload16").contentWindow.document.querySelectorAll(".english")
                        for (i = 0; i < y.length; i++) {
                            y[i].style.display = "none";
                        } 
                        var z = document.getElementById("onload16").contentWindow.document.querySelectorAll(".chinese")
                        for (i = 0; i < z.length; i++) {
                            z[i].style.display = "none";
                        } 
                    }
                    function iframeEnglish1(){
                        var x, y, z, i;
                        var x = document.getElementById("onload16").contentWindow.document.querySelectorAll(".nederlands")
                        for (i = 0; i < x.length; i++) {
                            x[i].style.display = "none";
                            
                        } 
                        var y = document.getElementById("onload16").contentWindow.document.querySelectorAll(".english")
                        for (i = 0; i < y.length; i++) {
                            y[i].style.display = "flex";
                            y[i].style.color = "blue";
                            y[i].style.fontSize = "20px";
                        } 
                        var z = document.getElementById("onload16").contentWindow.document.querySelectorAll(".chinese")
                        for (i = 0; i < z.length; i++) {
                            z[i].style.display = "none";
                        } 
                    }
                    function iframeChinese1(){
                        var x, y, z, i;
                        var x = document.getElementById("onload16").contentWindow.document.querySelectorAll(".nederlands")
                        for (i = 0; i < x.length; i++) {
                            x[i].style.display = "none";
                        } 
                        var y = document.getElementById("onload16").contentWindow.document.querySelectorAll(".english")
                        for (i = 0; i < y.length; i++) {
                            y[i].style.display = "none";
                        } 
                        var z = document.getElementById("onload16").contentWindow.document.querySelectorAll(".chinese")
                        for (i = 0; i < z.length; i++) {
                            z[i].style.display = "flex";
                            z[i].style.color = "yellow";
                            z[i].style.fontSize = "20px";
                        } 
                    }
                </script>
                
            

Example 5

p.s. demo_4 is used as iframe content.



Click the buttons to get the text in the appropriate language.